package development.app;

import java.util.Vector;

import state.Clip;
import state.DrawListener;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.SMSHandler;
import state.SendSMSListener;
import state.Sprite;
import state.component.Event;
import state.component.EventListener;
import state.component.GameScrollBar;
import state.component.GridMenu;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.socket.MapDataPackage;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.NumberUtil;
import state.util.array.ByteArray;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.Global;
import development.Utils;
import development.bean.Category;
import development.bean.SMSServiceCommand;
import development.bean.Subscription;
import development.group.FrmGroupThoiTietTinTuc;
import development.socket.SocketClientUtil;

public class FrmTinTuc extends GameForm implements EventListener, SendSMSListener{
  public static final int NEWS_CATEGOGRY_REQUEST = 550;
  public static final int NEWS_CATEGOGRY_RESPONSE = 551;
  public static final int NEWS_CONTENT_REQUEST = 552;
  public static final int NEWS_CONTENT_RESPONSE = 553;
  public static final int CANCEL_REQUEST = 554;
  public static final int CANCEL_RESPONSE = 555;

  private final String FIRST_CATEGORY_CODE = "NEWS";
  private static final int DY = 25;

  private ImageText text8;
  private ImageText text11;
  private Hashtable imageContent = null;
  private Vector content;
  private int categoryIndex;
  private String type;
  private Hashtable logAction = null;
  private int currentAction;
  private String contentTitle;
  private int CATEGORY_IMAGE_HEIGHT;
  private Vector categoriesPath;
  private int dy;

  private final int DEFAULT_TEXT_X = 5;
  private GameScrollBar scrollBar;
  private Clip textView;

  private Vector categories;

  private final String WAITING_MESSAGE = "Xin chờ trong giây lát...";
  private int packageNumber;
  private int totalPackage;
  private int percent;
  
  private GridMenu gridMenu;

  private static GameForm singleton;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmTinTuc();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    categories = new Vector();
    content = new Vector();
    imageContent = new Hashtable();
    logAction = new Hashtable();
    categoriesPath = new Vector();
    currentAction = 1;
    type = "category";
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    text11 = FontManager.getFont(FontManager.FONT_SIZE_11);
    CATEGORY_IMAGE_HEIGHT = 50 + 25;
    dy = DY;
    request(NEWS_CATEGOGRY_REQUEST, new StringArray(new String[] { FIRST_CATEGORY_CODE },1));
    DrawUtils.setBottomBar(_manager, "Menu chính", null, "Trở về");
    //manager.enableTouchPad();
    
    gridMenu = new GridMenu(_manager, null, null, 1, 0, DrawUtils.getTopBarHeight(), Global.getDefaultAvatar().getHeight() + 5, Global.getDefaultAvatar().getWidth() + 5, this);
    gridMenu.setVisible(false);
    
    textView = new Clip(DEFAULT_TEXT_X, dy, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - dy - 10);
    scrollBar = new GameScrollBar(Constants.SCREEN_WIDTH - 5, 25, 5, Constants.SCREEN_HEIGHT - 50, textView, _manager);
  }

  public void draw(Graphics g) {
    DrawUtils.drawAppBackground(g);
    if (categories.isEmpty()) {
      text8.drawString2(g, WAITING_MESSAGE, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2, GameConstants.TOP_HCENTER_ANCHOR);
    }
    if (type.equals("category") && categories.size() != 0) {
      drawCategory(g);
    }
    if (type.equals("content") && content != null && content.size() > 0) {
      drawContent(g);
    }
    drawMenu(g);
    text8.drawString2(g, GameStringUtils.join(categoriesPath, "-"), GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 5, GameConstants.TOP_HCENTER_ANCHOR);
  }

  private void drawMenu(Graphics g) {
    if (!isLoadingCompleted()) {
      DrawUtils.getBottomBar(_manager).setRightLabel("Dừng tải");
    } else {
      DrawUtils.getBottomBar(_manager).setLabels("Menu chính", "", "Trở về");
    }
    if (type.equals("content")) {
      DrawUtils.getBottomBar(_manager).setCenterLabel(null);
    }
  }

  private void drawContent(Graphics g) {
    int textY = dy;
    text11.setBold(true);
    if (contentTitle != null && !contentTitle.equals("")) {
      textY = text11.drawParagraph(g, contentTitle, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - DEFAULT_TEXT_X, DEFAULT_TEXT_X, textY);
      textY = textY + 20;
      g.setColor(0xC0C0C0);
      g.drawLine(0, textY - 7, GameConstants.SCREEN_WIDTH, textY - 7);
    }

    for (int i = 0; i < content.size(); i++) {
      String str = (String) content.elementAt(i);
      GameImage image = null;
      if (str.toUpperCase().endsWith(".JPG") || str.toUpperCase().endsWith(".JPEG") || str.toUpperCase().endsWith(".PNG")) {
        image = (GameImage) imageContent.get(str);
      }
      if (image != null) {
        g.drawImage(image, DEFAULT_TEXT_X, textY + 10, GameConstants.TOP_LEFT_ANCHOR);
        textY = textY + image.getHeight() + 20;
      } else {
        textY = text11.drawParagraph2(g, str, GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - DEFAULT_TEXT_X, DEFAULT_TEXT_X, textY, scrollBar);
      }
    }
    text8.drawString3(g, ".", GameColor.WHITE_CODE, 0, textY + 30, Constants.TOP_LEFT_ANCHOR, scrollBar);
    scrollBar.draw(g);
  }

  private void drawCategory(Graphics g) {
//    int textY = dy;
//    int index = 0;
//    if (categoryIndex == 0) {
//      dy = DY;
//    }
//    for (int i = 0; i < categories.size(); i++) {
//      Category category = (Category) categories.elementAt(i);
//      g.drawImage(category.image, 0, textY, GameConstants.TOP_LEFT_ANCHOR);
//      if (!category.hasChild) {
//        text8.drawString(g, category.name, Color.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
//      } else {
//        text8.drawString(g, category.name, Color.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
//      }
//      if (categoryIndex == index) {
//        g.setColor(0x53A4CF);
//        g.fillRect(0, textY - 7, GameConstants.SCREEN_WIDTH, Global.getDefaultAvatar().getHeight() + 25);
//        g.drawImage(category.image, 0, textY, GameConstants.TOP_LEFT_ANCHOR);
//        if (!category.hasChild) {
//          text8.drawString(g, category.name, Color.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
//        } else {
//          text8.drawString(g, category.name, Color.YELLOW_CODE, category.image.getWidth() + 5, textY + category.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
//        }
//      }
//      if (!category.hasChild) {
//        text8.drawString(g, "Chi tiết >>", Color.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, textY + category.image.getHeight(), GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
//      }
//      g.setColor(0xC0C0C0);
//      g.drawLine(0, textY - 7, GameConstants.SCREEN_WIDTH, textY - 7);
//      textY = textY + Global.getDefaultAvatar().getHeight() + 25;
//      index++;
//    }
//    g.drawLine(0, textY - 7, GameConstants.SCREEN_WIDTH, textY - 7);
//    text8.drawString(g, "", Color.WHITE_CODE, 0, textY, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
//    scrollBar.draw(g);
//    if (percent < 100) {
//      DrawUtils.getBottomBar(manager).setCenterLabel(percent + "%");
//    } else {
//      DrawUtils.getBottomBar(manager).setCenterLabel("");
//    }
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    MapDataPackage mapDataPackage = MapDataPackage.getMapPackage(dataPackage);
    type = mapDataPackage.popString("type");
    if (type.equals("-1")) {
      Global.alert.showAlert2(this, GameAlert.OK_TYPE, "Chưa có dữ liệu cho mục này", -1);
      return;
    }
    GameGlobal.systemCanvas.hideAlert();
    switch (header) {
    case NEWS_CATEGOGRY_RESPONSE:
      Category category = new Category();
      category.id = mapDataPackage.getString("id");
      category.code = mapDataPackage.getString("code");
      category.name = mapDataPackage.getString("name");
      ByteArray btImage = mapDataPackage.getByteArray("avatarImage");
      category.image = ImageUtil.resizeImage2(GameImage.createImage(btImage, 0, btImage.len()), 50, 50);
      category.hasChild = NumberUtil.parseInt(mapDataPackage.getString("child")) > 0;
      CATEGORY_IMAGE_HEIGHT = 50;
      packageNumber = mapDataPackage.getInt("packageNumber");
      totalPackage = mapDataPackage.getInt("totalPackage");
      percent = (packageNumber * 100) / totalPackage;
      categories.addElement(category);
      gridMenu.setHozDistance(category.image.getHeight() + 5);
      gridMenu.setDisplayTitle(false);
      gridMenu.setVisible(true);
      Sprite sprite = new Sprite(null, null, 0, 0, Constants.TOP_LEFT_ANCHOR);
      sprite.setSize(GameConstants.SCREEN_WIDTH - 10, Global.getDefaultAvatar().getHeight() + 5);
      sprite.setId((byte) (categories.size() - 1));
      gridMenu.addSpriteItem(sprite, category.id);
      sprite.setDrawListener(new DrawListener() {
        public void paint(Sprite source, Graphics g) {
          int index = source.getId();
          Category category1 = (Category) categories.elementAt(index);
          g.drawImage(category1.image, 0, source.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
          if (!category1.hasChild) {
            text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          } else {
            text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
          }
          if (gridMenu.getCurrentSelectedIndex() == index) {
            g.setColor(0x53A4CF);
            g.fillRect(0, source.getRealY() - 7, GameConstants.SCREEN_WIDTH, Global.getDefaultAvatar().getHeight() + 5);
            g.drawImage(category1.image, 0, source.getRealY(), GameConstants.TOP_LEFT_ANCHOR);
            if (!category1.hasChild) {
              text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 50, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            } else {
              text8.drawString3(g, category1.name, GameColor.YELLOW_CODE, category1.image.getWidth() + 5, source.getRealY() + category1.image.getHeight() / 3, GameConstants.TOP_LEFT_ANCHOR, scrollBar);
            }
          }
          if (!category1.hasChild) {
            text8.drawString3(g, "Chi tiết >>", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH - 5, source.getRealY() + 30, GameConstants.TOP_RIGHT_ANCHOR, scrollBar);
          }
          g.setColor(0xC0C0C0);
          g.drawLine(0, source.getRealY() - 7, GameConstants.SCREEN_WIDTH, source.getRealY() - 7);
          
          if(index == gridMenu.getNumberOfItem() - 1){
            g.setColor(0xC0C0C0);
            g.drawLine(0, source.getRealY() + category1.image.getHeight() + 2, GameConstants.SCREEN_WIDTH, source.getRealY() + category1.image.getHeight() + 2);
          }
        }
      });
      break;
    case NEWS_CONTENT_RESPONSE:
      Vector names = mapDataPackage.getNames();
      String keyContent = null;
      percent = (packageNumber * 100) / totalPackage;
      if (!names.isEmpty()) {
        keyContent = mapDataPackage.getNames().elementAt(0).toString();
      }
      if (keyContent == null || keyContent.equals("")) {
        return;
      }
      int type1 = mapDataPackage.getTypeOf(keyContent);
      if (type1 == MapDataPackage.STRING_TYPE) {
        if (!content.contains(mapDataPackage.getString(keyContent))) {
          content.addElement(mapDataPackage.getString(keyContent));
        }
      } else {
        ByteArray value = mapDataPackage.getByteArray(keyContent);
        GameImage image = ImageUtil.resizeImage2(GameImage.createImage(value, 0, value.len()),Constants.SCREEN_WIDTH - DEFAULT_TEXT_X, Constants.SCREEN_HEIGHT - 25);
        imageContent.put(keyContent, image);
        if (!content.contains(keyContent)) {
          content.addElement(keyContent);
        }
      }
      _manager.enableTouchPad();
      break;
    case CANCEL_RESPONSE:
      packageNumber = totalPackage;
      break;
    }
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.LEFT:
      FrmGroupThoiTietTinTuc.setTab(0);
      break;
    case Key.RIGHT:
      FrmGroupThoiTietTinTuc.setTab(2);
      break;
    case Key.DOWN:
      if (!categories.isEmpty()) {
        if (type.equals("category")) {
          if (categoryIndex < categories.size() - 1) {
            categoryIndex++;
          }
        }
      }
      if (type.equals("category")) {
        if (categories.size() * (CATEGORY_IMAGE_HEIGHT + 25) < GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight()) {
          return;
        }
        if (scrollBar.canScrollUp()) {
          dy = dy - (CATEGORY_IMAGE_HEIGHT + 25);
        }
      }
      if (type.equals("content")) {
        if (scrollBar.canScrollUp()) {
          dy -= 10;
        }
      }
      break;
    case Key.UP:
      if (!categories.isEmpty()) {
        if (categoryIndex > 0) {
          categoryIndex--;
        } else if (categoryIndex == 0) {
        }
      }
      if (type.equals("content")) {
        if (scrollBar.canScrollDown()) {
          dy += 10;
        } else {
          // dy = textView.y;
        }
      }
      if (type.equals("category")) {
        if (scrollBar.canScrollDown()) {
          dy = dy + (CATEGORY_IMAGE_HEIGHT + 25);
        }
      }
      break;
    case Key.FIRE:
//      currentAction++;
//      dy = DY;
//      Category category = (Category) categories.elementAt(categoryIndex);
//      if (category.hasChild) {
//        if (!categoriesPath.contains(category.name)) {
//          categoriesPath.addElement(category.name);
//        }
//        request(NEWS_CATEGOGRY_REQUEST, new String[] { category.code });
//        clearCategory();
//      } else {
//        request(NEWS_CONTENT_REQUEST, category.id);
//        Global.alert.showAlert(this, Alert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(10000);
//      }
      process(gridMenu.getCurrentSelectedIndex());
      break;
    case Key.SOFT_LEFT:
      DataPackage dataPackage = DataPackage.createDataPackage1(CANCEL_REQUEST);
      dataPackage.putString(type);
      Global.appClient.write(dataPackage);
      parentGroup.goBack();
      break;
    case Key.SOFT_RIGHT:
      if (isLoadingCompleted()) {
        content.removeAllElements();
        imageContent.clear();
        contentTitle = null;
        categoryIndex = 0;
        if(type.equals("content")){
          _manager.disableTouchPad();
        }
        if (currentAction > 1) {
          clearCategory();
          back();
          if (type.equals("category")) {
            categoriesPath.removeElementAt(categoriesPath.size() - 1);
          }
        } else {
          parentGroup.goBack();
        }
      } else {
        packageNumber = totalPackage;
        dataPackage = DataPackage.createDataPackage1(CANCEL_REQUEST);
        dataPackage.putString(type);
        Global.appClient.write(dataPackage);
      }
      break;
    default:
      break;
    }
  }

  public void keyRepeated(int keyCode) {
    switch (keyCode) {
    case Key.DOWN:
      if (type.equals("content")) {
        if (scrollBar.canScrollUp()) {
          dy -= 10;
        }
      }
      break;
    case Key.UP:
      if (type.equals("content")) {
        if (scrollBar.canScrollDown()) {
          dy += 10;
        } else {
        }
      }
      break;
    }
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == -1) {
      if (currentAction > 1) {
        clearCategory();
        back();
      }
    }else if (alertId == 10000 && eventType == GameAlert.YES_BUTTON) {
      SMSServiceCommand sms = Utils.getSMSServiceCommand("GOINEWS", "GOI NEWS");
      if (sms != null) {
        SMSHandler.getInstance(this).sendMsg(sms.serviceNumber, sms.command);
      }
    }
  }

  private boolean isLoadingCompleted() {
    return packageNumber == totalPackage;
  }

  private void request(int header, StringArray parameters) {
    DataPackage dataPackage = DataPackage.createDataPackage1(header);
    for (int i = 0; i < parameters.len(); i++) {
      dataPackage.putString(parameters.array[i]);
    }
    Global.appClient.write(dataPackage);
    logAction.put(String.valueOf(currentAction), buildLogAction(header, parameters));
  }

  private void request(int header, String param) {
    request(header, new StringArray(new String[] { param },1));
  }

  private String buildLogAction(int requestType, StringArray parameters) {
    StringBuffer sb = new StringBuffer();
    sb.append(String.valueOf(requestType));
    sb.append(",");
    for (int i = 0; i < parameters.len(); i++) {
      sb.append(parameters.array[i]);
      sb.append(",");
    }
    if (sb.toString().endsWith(",")) {
      sb.deleteCharAt(sb.length() - 1);
    }
    return sb.toString();
  }

  private void back() {
    currentAction--;
    dy = DY;
    String values = (String) logAction.get(String.valueOf(currentAction));
    StringArray requestParams = GameStringUtils.split(values, ",");
    int request = NumberUtil.parseInt(requestParams.get(0));

    request(request, new StringArray(new String[] { requestParams.get(1) },1));
  }

  private void clearCategory() {
    gridMenu.clearData();
    categories.removeAllElements();
    categoryIndex = 0;
    dy = DY;
    Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(10000);
  }

  public void destroy() {
    text11 = null;
    imageContent = null;
    content = null;
    type = null;
    logAction = null;
    contentTitle = null;
    categoriesPath = null;
    scrollBar = null;
    textView = null;
    categories = null;
    gridMenu = null;
  }

  public void onActionPerform(Event event) {
    if (event.getSource() == gridMenu) {
      process(gridMenu.getCurrentSelectedIndex());
    }
  }
  private void process(int index) {
    Subscription sub = Utils.getSubcription("GOINEWS", "GOI NEWS");
    if (sub == null || sub.status == Subscription.EXPIRED) {
      SMSServiceCommand sms = Utils.getSMSServiceCommand("GOINEWS", "GOI NEWS");
      if (sms != null) {
        Global.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create1( "Phí dịch vụ 10 gold","Bạn đồng ý không?" ), 10000);
        return;
      }
    }
    currentAction++;
    dy = DY;
    Category category = (Category) categories.elementAt(index);
    if (category.hasChild) {
      if (!categoriesPath.contains(category.name)) {
        categoriesPath.addElement(category.name);
      }
      request(NEWS_CATEGOGRY_REQUEST, new StringArray(new String[] { category.code },1));
      clearCategory();
    } else {
      request(NEWS_CONTENT_REQUEST, category.id);
      gridMenu.setVisible(false);
      Global.alert.showAlert2(this, GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang tải...", 99).setAlertTimeOut(10000);
    }
  }

  public void onSendSMSFail() {
    Global.alert.showAlert(this, GameAlert.OK_TYPE, "Đăng ký thất bại");
  }

  public void onSendSMSSuccess() {
    Global.alert.showAlert3(this, GameAlert.OK_TYPE, StringArray.create2("Đăng ký thành công","Xin mời bạn quay lại","trong ít phút"));
    SocketClientUtil.createSubscription("GOINEWS", "GOI NEWS");
  }
}
